const express = require('express');
const router = express.Router();
const md5 = require('blueimp-md5');

const {UserModel,ChatModel} = require('../db/models');

router.get("/aaaa", (req, res) => {
    res.send("aaaa")
})

router.post("/register", (req, res) => {
    const {
        password,
        username,
        type
    } = req.body;

    UserModel.findOne({ username }, (err, user) => {
        if(err){
            console.log(err)
            return 
        }
        if (user) {
            res.send({ code: 3, msg: "用户存在", data: null })
        }else{
            new UserModel({
                password: md5(password),
                username,
                type
            }).save((err, user) => {
                if(err){
                    console.log(err)
                    return 
                }
                else{
                    res.cookie("user_id", user._id, { maxAge: 1000 * 60 * 60 * 24 })
                    res.send({ code: 0, data: user, msg: "success" })
                }
            });
        }
    })

})

router.post("/getUserByCookie",(req, res) => {
    const {user_id} = req.cookies;
    if(!user_id){
        return res.send({code: 3, msg: "please login first"})
    }
    UserModel.findById(user_id,(err, user) => {
        if(err){
            return res.send({code: 3,  msg: "not found"})
        }
        res.send({code: 0,data: user})
    })
})

// username & paddword 登陆
router.post("/login", (req, res) => {
    const {
        password,
        username,
    } = req.body;

    UserModel.findOne({ username, password: md5(password) }, (err, user) => {
        if (user) {
            res.cookie('user_id', user._id, {maxAge: 1000*60*60*24})
            res.send({ code: 0, msg: "login success", data: user })
        } else{
            res.send({ code: 3, msg: "user has not register or password error" });
        }
    }
    )
})

// update user touxiang
router.post("/update",(req, res) => {
    const {user_id} = req.cookies;
    const user = req.body;
    if(user_id){
        UserModel.findByIdAndUpdate({_id:user_id},user,{new: true},(err,newUser) => {
            console.log(newUser);
            if(err ){
                res.clearCookie('user_id')
                return res.send({code: 3,msg: "please relogin!"})
            }
            res.send({code: 0,data:newUser})

        })
    }else{
        res.send({code: 3,msg: "please login first !"})
    }
    
})

router.post("/getUserListByType",(req, res) => {
    const {type} = req.body;
    UserModel.find({type},(err, users) => {
        if(err){
            return res.send({code: 3,errmsg: err})
        }
        return res.send({code: 0, data: users})
    })
})

// 获取当前用户的消息信息
router.post("/getMsgList",(req, res) => {
    const userid = req.cookies.user_id;
    UserModel.find((err, users) => {
        if(err){
            return res.send({code: 0,errmes: err})
        }
        let usersObj = {}
        users.forEach(i => usersObj[i._id] = i)
        ChatModel.find({'$or':[{from:userid},{to:userid}]},(err, chats) => {
            if(err){
                return res.send({code: 0,errmes: err})
            }
            res.send({code: 0,data: {users: usersObj,chatMsg: chats}})
        })
    })
})

router.post("/sendMsg",(req,res) => {
    const {from,to,content} = req.body;
    const createTime = Date.now()
    
})

router.post("/readMsg",(req,res) => {
    const {from} = req.body;
    const to = req.cookies.user_id;
    ChatModel.updateMany({from,to,read: false},{read: true},(err,doc) => {
        console.log(doc)
        res.send({code: 0,data: doc.nModified})
    })
})



module.exports = router;